<?php


namespace app\api\controller;


use app\admin\model\express\Package;
use app\admin\model\express\Subscribe;
use app\admin\model\PackageExpress;
use app\admin\model\User;
use app\api\model\OrderAddress;
use app\api\model\PackageAddress;
use app\api\model\Service;
use app\api\model\TemplateSub;
use app\common\controller\Api;
use app\common\library\Log;
use app\common\model\Category;
use common\models\OrderExpress;
use common\models\UuOrder;
use fast\Express100;
use fast\Tree;
use think\Cache;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Order extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['category','couponlist','express_type', 'counter', 'js', 'excoupon','sharecoupon', 'sharecoupon', 'area', 'p',
        'packagetrack', 'packageDetail', 'findForExpress', 'sign','orderDetail','test','payInfo','getExpressInfo','packDetail','addPack','editPack','packList','userPackList','getExpressInfo1'
    ];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    // 获取商品分类
    public function category()
    {
        $tree    = Tree::instance();
        $cateArr = [];
        foreach (collection(Category::order('weigh desc,id desc')->select())->toArray() as $category) {
            $cateArr[] = [
                'id' => $category['id'],
                'pid' => $category['pid'],
                'text' => $category['name']
            ];
        }
        $tree->init($cateArr, 'pid');
        $categorylist = $tree->getCateTreeArray(0);
        $this->success('ok', $categorylist);
    }

    // 获取澳洲地区
    public function area()
    {
        $arealist = Cache::get('arealist', '');
        if (!$arealist) {
            $tree    = Tree::instance();
            $areaArr = [];
            foreach (collection(Db::name('area_au')->order('id asc')->select())->toArray() as $area) {
                $areaArr[] = [
                    'id' => $area['id'],
                    'pid' => $area['parent_id'],
                    'text' => $area['name']
                ];
            }
            $tree->init($areaArr, 'pid');
            $arealist = $tree->getCateTreeArray(0);
            Cache::set('arealist', $arealist);
        }

        $this->success('ok', $arealist);
    }

    //用户在线订单预报
    public function forecastorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $user_id = $this->auth->id;
            Db::startTrans();
            try {
                if (!$data['order']['from_express_no']) {
                    $this->error('运单号不能为空');
                }
                $count = Db::name('express_order')->where('from_express_no', $data['order']['from_express_no'])->count();
                if ($count > 0) {
                    $this->error('该运单号已存在');
                }
                $nowTime = time();
                $data['order']['is_forecast'] = 'yes';  //是否预报 yes是，no不是
                $data['order']['user_id']     = $user_id;
                $data['order']['order_no']    = orderOn($user_id);
                $data['order']['createtime']  = $nowTime;
                $data['order']['updatetime']  = $nowTime;
                $data['order']['status']      = "created";

                $order_id  = Db::name('express_order')->insertGetId($data['order']);
                $goodsList = [];
                foreach ($data['goods'] as $goods) {
                    $validate = new \think\Validate([
                        'name|商品名称' => 'require',
                    ]);
                    if (!$validate->check($goods)) {
                        $this->error($validate->getError());
                    }
                    $goodsList[] = [
                        'order_id' => $order_id,
                        'name' => $goods['name'],
                        'number' => $goods['number']??1,
                    ];
                }
                $goodsData = model('app\api\model\OrderGoods')->saveAll($goodsList);
                if ($data['order']['is_now'] == 'yes') {
                    $address = model('app\api\model\Address')->get($data['address_id']);
                    //检查
                    if (!$address) {
                        $this->error('收货地址不存在');
                    }
                    $orderAddress = model('app\api\model\OrderAddress')->get([
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                    ]);
                    if(empty($orderAddress)){
                        $orderAddress = new \app\admin\model\express\Order();
                    }
                    $orderAddress->allowField(true)->save([
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['area'],
                        'address' => $address['address'],
                        'zip_code' => $address['zip_code'],
                        'province_index' => $address['province_index'],
                        'city_index' => $address['city_index'],
                        'area_index' => $address['area_index'],
                    ]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('ok');
        }
    }

    //用户在线订单预报
    public function forecastorder1()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $user_id = $this->auth->id;
            Db::startTrans();
            try {
                if (!$data['order']['from_express_no']) {
                    $this->error('运单号不能为空');
                }
                $count = Db::name('express_order')->where('from_express_no', $data['order']['from_express_no'])->count();
                if ($count > 0) {
                    $this->error('该运单号已存在');
                }
                $nowTime = time();
                $data['order']['is_forecast'] = 'yes';  //是否预报 yes是，no不是
                $data['order']['user_id']     = $user_id;
                $data['order']['order_no']    = orderOn($user_id);
                $data['order']['createtime']  = $nowTime;
                $data['order']['updatetime']  = $nowTime;
                $data['order']['status']      = "created";

                $order_id  = Db::name('express_order')->insertGetId($data['order']);
                $goodsList = [];
                foreach ($data['goods'] as $goods) {
                    $validate = new \think\Validate([
                        'name|商品名称' => 'require',
                    ]);
                    if (!$validate->check($goods)) {
                        $this->error($validate->getError());
                    }
                    $goodsList[] = [
                        'order_id' => $order_id,
                        'name' => $goods['name'],
                        'number' => $goods['number']??1,
                    ];
                }
                $goodsData = model('app\api\model\OrderGoods')->saveAll($goodsList);
                if ($data['order']['is_now'] == 'yes') {
                    $address = model('app\api\model\Address')->get($data['address_id']);
                    //检查
                    if (!$address) {
                        $this->error('收货地址不存在');
                    }
                    $orderAddress = model('app\api\model\OrderAddress')->get([
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                    ]);
                    if(empty($orderAddress)){
                        $orderAddress = new \app\admin\model\express\Order();
                    }
                    $orderAddress->allowField(true)->save([
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['area'],
                        'address' => $address['address'],
                        'zip_code' => $address['zip_code'],
                        'province_index' => $address['province_index'],
                        'city_index' => $address['city_index'],
                        'area_index' => $address['area_index'],
                    ]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('ok');
        }
    }

    //用户完善订单
    public function complete()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $user    = $this->auth->getUser();
            $user_id = $user['id'];
            Db::startTrans();
            try {
                $id = $data['order']['id'];
                $s  = Db::name('express_order')->where('id', $id)->value('status');
                if ($s != 'created') {
                    $this->error('已经完善过了');
                }
                $data['order']['is_forecast'] = 'no';
                if (!$data['order']['is_now']) {
                    $this->error('是不是立即发货');
                }
                if (!$data['order']['is_now']) {
                    $this->error('是不是立即发货不能为空');
                }
                if ($data['order']['is_now'] == 'yes') { //如果是立即发货，立即生成包裹
                    //成生包裹
                    $packaage_no = orderOn($user_id);
                    $packaage_id = Db::name('express_package')->insertGetId([
                        'package_no' => orderOn($user_id),
                        'user_id' => $user_id,
                        'is_delivery' => 1,
                        'status' => 'complete',
                        'createtime' => time(),
                        'updatetime' => time(),
                    ]);
                }
                $order = model('app\api\model\Order')->get([
                    'id' => $data['order']['id'],
                    'user_id' => $user_id
                ]);
                if (in_array($order['status'], ['successpay', 'delivered'])) {
                    $this->error('该订单已支付,不可进行修改');
                }

                $data['order']['status'] = 'complete';
                if ($data['order']['is_now'] == 'yes') {
                    $data['order']['package_id'] = $packaage_id;
                    $data['order']['package_no'] = $packaage_no;
                }
                unset($data['order']['from_express_no']);
                $order->allowField(true)->save($data['order']);
                $goodsList = [];
                model('app\api\model\OrderGoods')->where('order_id', $order->id)->delete();
                foreach ($data['goods'] as $goods) {
                    $validate = new \think\Validate([
                        'name|商品名称' => 'require',
                        //   'category_id|分类' => 'require',
                        //'brand|品牌' => 'require',
                        //'sku|规格' => 'require',
                        //'weight|商品净含量' => 'require|number',
                        //  'number|数量' => 'require|number',
                        //   'price|价格' => 'float|number',
                    ]);
                    if (!$validate->check($goods)) {
                        $this->error($validate->getError());
                    }
                    $goodsList[] = [
                        'order_id' => $order->id,
                        'name' => $goods['name'],
                        //   'category_id' => $goods['category_id'],
                        //   'brand' => $goods['brand'],
                        //'sku' => $goods['sku'],
                        //'weight' => $goods['weight'],
                        //    'number' => $goods['number'],
                        //      'price' => $goods['price'],
                        //  'category_ppindex' => $goods['category_ppindex'] ?? 0,
                        //    'category_pindex' => $goods['category_pindex'] ?? 0,
                        //   'category_index' => $goods['category_index'] ?? 0,
                        //'index' => $goods['index'],
                        //'unit' => $goods['unit'] ?? 'g',
                        //'description' => $goods['description'] ?? 'g',
                        //'number_unit' => $goods['number_unit'] ?? '个',
                        //'rule_id' => Category::where('id',$goods['category_id'])->value('rule_id')
                    ];
                }
                $goodsData = model('app\api\model\OrderGoods')->saveAll($goodsList);

                if ($data['order']['is_now'] == 'yes') {
                    $address = model('app\api\model\Address')->get($data['address_id']);
                    if (!$address) {
                        $this->error('收货地址不存在');
                    }
                    $orderAddress = model('app\api\model\OrderAddress')->get([
                        'order_id' => $order->id,
                        'user_id' => $user_id,
                    ]);
                    if ($orderAddress) {
                        $orderAddress->allowField(true)->save([
                            'order_id' => $order->id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                            'province_index' => $address['province_index'],
                            'city_index' => $address['city_index'],
                            'area_index' => $address['area_index'],
                        ]);
                    } else {
                        model('app\api\model\OrderAddress')->allowField(true)->save([
                            'order_id' => $order->id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                        ]);
                    }

                    $packAddressM = new PackageAddress();
                    $packAddress = $packAddressM->get([
                        'package_id' => $packaage_id,
                        'user_id' => $user_id,
                    ]);
                    if ($packAddress) {
                        $packAddressM->allowField(true)->save([
                            'package_id' => $packaage_id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                            'province_index' => $address['province_index'],
                            'city_index' => $address['city_index'],
                            'area_index' => $address['area_index'],
                        ]);
                    } else {
                        $packAddressM = new PackageAddress();
                        $packAddressM->allowField(true)->save([
                            'package_id' => $packaage_id,
                            'user_id' => $user_id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'province' => $address['province'],
                            'city' => $address['city'],
                            'area' => $address['area'],
                            'address' => $address['address'],
                            'zip_code' => $address['zip_code'],
                        ]);
                    }
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('ok');
        }
        $this->error('请求错误');
    }

    // 我的订单
    public function myOrder()
    {
        $type = $this->request->param('type');//1:未入仓  2:在仓
        if ($type == 1) {
            //未入仓
            $where['order.is_forecast'] = 'yes';//预报订单
            $where['order.status']      = 'created';//没有完善
            $where['order.package_id']  = 0;//没有完善
        } elseif ($type == 2) {
            //在仓
            $where['order.status']     = 'complete';//已经完善
            $where['order.package_id'] = 0;//没有打包
            $where['order.is_now']     = 'no';//不是立即发货
        } elseif ($type == 3) {
            //待完善
            $where['order.status']      = 'created';
            $where['order.is_forecast'] = 'no';
            $where['order.package_id']  = 0;//没有 完善
        }

        $where['order.user_id'] = $this->auth->id;

        $list = model('app\api\model\Order')
            ->with(['address'])->with(['goods'])
            ->where($where)
            //->where('address.name|address.mobile|address.address|address.idcard','like','%'.$keywords.'%')
            ->order('order.updatetime desc')
            //->select();
            ->paginate(1000)->each(function ($item, $key) {
                $item->createtime = date('Y-m-d H:i:s', $item['createtime']);
                $item->updatetime = date('Y-m-d H:i:s', $item['updatetime']);
                $item->goodlist   = array_column($item->goods, 'name');
                return $item;
            });


        foreach ($list as $row) {
        //    $row->goodlist   = array_column($row->goods, 'name');
        //    $row->createtime = date('Y-m-d H:i:s', $row['createtime']);
        //    $row->updatetime = date('Y-m-d H:i:s', $row['updatetime']);
            $row->getRelation('address')->visible(['name', 'mobile', 'province', 'city', 'area', 'address', 'idcard', 'idcard_front', 'idcard_reverse', 'zip_code']);
            //  $row->getRelation('goods')->visible(['name','brand']);
        }

        foreach ($list as &$row) {
            if($row["delivery_weight"] == 0){
                $row["delivery_weight"] = "";
            }
            // $row->getRelation('goods')->visible(['name']);
            //   $row->getRelation('goods');
        }
        $this->success('ok', $list);
    }

    /**
     *1.待打包
     *2.待支付
     *3.待发货
     *4.转运中
     *5.已签收
     */
    public function mypackage()
    {
        $user = $this->auth->id;
        $type = $this->request->post('type', 0);
        $where['user_id'] = ['=', $user];
        switch ($type) {
            case 1:
                $where['status'] = ['in',['complete','waitpackage']];//
                break;
            case 2:
                $where['status'] = 'waitingpay';//待支付//successpay
                break;
            case 3:
                $where['status'] = 'successpay';//待支付//
                break;
            case 4:
                $where['status'] = 'delivered';//转运中
                break;
            case 5:
                $where['status'] = 'sign';//转运中
                break;
            case 0:
                $where['createtime'] = ['>', 0];
        }


        $list = Db::name('express_package')->where($where)->order('createtime desc')->paginate()->each(function ($item, $key) {
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
            $item['updatetime'] = date('Y-m-d H:i:s', $item['updatetime']);
            $item['orderlist'] = Db::name('express_order')->where('package_id', $item['id'])->select();
            $item['address']   = Db::name('express_package_address')->field(['name', 'mobile','country','province', 'city', 'area', 'address', 'idcard', 'idcard_front', 'idcard_reverse', 'zip_code'])
                ->where('package_id', $item['id'])->find();
            return $item;
        });
        $this->success('', $list);
    }

    // 订单详情
    public function orderDetail()
    {
        $id = (int)$this->request->post('id');
        if($id<1){
            $id = (int)$this->request->get('id');
        }
        $order     = model('app\api\model\Order')->get($id);
        if(empty($order)){
            $this->error('订单不存在');
        }
        $goodsData = model('app\api\model\OrderGoods')->where(['order_id' => $id])->select();
        foreach ($goodsData as $goods) {
            $goods['category_name'] = Category::where('id', $goods['category_id'])->value('name');
        }
        $goodsData        = collection($goodsData)->toArray();
        $order['goods']   = $goodsData;
        $order['address'] = model('app\api\model\OrderAddress')->where('order_id', $id)->find();
        $order['service'] = model('app\api\model\Service')->where('id', 'in', $order['service_ids'])->select();
        $this->success('ok', $order);
    }

    // 包裹详情
    public function packageDetail()
    {
        $id = (int)$this->request->param('id');
        $user_id = $this->auth->id;
        $express_package = Db::name('express_package')->find(['id'=>$id,'user_id'=>$user_id]);
        if(empty($express_package)){
            $this->error("包裹不存在");
        }
        //状态:0=已入库,1=已预报,2=包裹已出库,3=正在发往澳洲,4=包裹清关中,5=包裹清关完成，等待发往指定地点,6=包裹已抵达指定自提点，等待顾客取件,7=已签收
        $state_ar = (new Package())->getStateList();
        $express_package['state_text'] = $state_ar[$express_package['state']]??"";
        $express_package_address = Db::name('express_package_address')->where('package_id', $id)->find();
        $express_package['address'] = $express_package_address;
        $express_order = Db::name('express_order')->where('package_id', $id)->select();
        $order_goods = [];
        $orderlist = [];
        $order_weight = 0;
        foreach ($express_order as $key => $value) {
            $order_weight += sprintf("%.2f",$value["delivery_weight"]);
            $orderlist[] = $this->getorderdetail($value['id']);
            $order_goods = array_merge($order_goods, $this->getorderdetail($value['id'])['goods']);
            foreach ($order_goods as &$g) {
                $service_ids       = Db::name('express_order')->where('id', $g['order_id'])->value('service_ids');
                $ser               = Service::where('id', 'in', $service_ids)->field('name,price')->select();
                $g['service_text'] = $ser;
            }
        }

        $order_weight = sprintf("%.2f",$order_weight);
        $express_package['goods'] = $order_goods;
        $express_package['order_weight'] = $order_weight;

        $this->success('', $express_package);
    }

    //获取订单详情
    protected function getorderdetail($order_id)
    {
        $order     = model('app\api\model\Order')->get($order_id);
        $goodsData = model('app\api\model\OrderGoods')->where(['order_id' => $order_id])->select();
        foreach ($goodsData as $goods) {
            $goods['category_name'] = Category::where('id', $goods['category_id'])->value('name');
        }
        $goodsData        = collection($goodsData)->toArray();
        $order['goods']   = $goodsData;
        $order['address'] = model('app\api\model\OrderAddress')->where('order_id', $order_id)->find();
        $order['service'] = model('app\api\model\Service')->where('id', 'in', $order['service_ids'])->select();
        return $order;
    }

    // 获取增值服务
    public function serviceList()
    {
        $list = Service::where('status', 'normal')->select();
        $this->success('ok', $list);
    }

    // 工作人员--扫码包裹入库--添加订单
    public function add()
    {
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $params['user_id'] = Db::name('user')->where('member_id', $this->request->post('user_id'))->value('id');
        $params['from_express_no'] = $this->request->post('from_express_no');
        if(empty($params['from_express_no'])){
            $this->error('来源订单号不能为空');
        }
        $check_order = Db::name('express_order')->where(['from_express_no'=>$params['from_express_no']])->count();
        if($check_order){
            $this->error('来源单号已经存在');
        }
        $user  = User::get($params['user_id']);
        if (!$user) {
            $this->error('该用户不存在');
        }
        $params['worker_user_id'] = $this->auth->id;  //工作人员id,
        $params['from_express_name'] = '';
        $params['order_no']          = $params['user_id'];
        $weight                      = $this->request->param('weight');
        $image                      = $this->request->param('image');
        if(empty($image)){
            $this->error('请拍照上传图片');
        }
        $params['order_image'] = $image;
        $params['delivery_weight'] = $weight;
        $nowTime = time();
        $params['createtime'] = $nowTime;
        $params['updatetime'] = $nowTime;
        $order_id = Db::name('express_order')->insertGetId($params);
        if(empty($order_id)){
            $this->error('订单保存失败');
        }
        $subscribe = new Subscribe();
        $template_id = 'wxSCZ_IiXMVOSylHCNI7H0amN8OkF31BVCT3oZpyEXo';
        $page = 'pages/IndexServer/AddPackage/AddPackage?form_express='.$params['from_express_no']."&orderid=".$order_id .'&type=complete';
        $string = '包裹已入库';
        $data   = [
            'character_string1' => [
                'value' => $params['from_express_no']
            ],
            'thing3' => [
                'value' => $string
            ]
        ];
        $subscribe = $subscribe->push($params['user_id'], $template_id, $page, $data);
        $this->success();
    }



    // 称重&设置支付金额
    public function setWeight()
    {
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $from_express_no           = $this->request->post('from_express_no');
        $params['delivery_weight'] = $this->request->post('delivery_weight');
        $params['delivery_price']  = $this->request->post('delivery_price');
        $order = Db::name('express_package')->where('package_no', $from_express_no)->find();
        if (!$order) {
            $this->error('该订单不存在');
        }
        if ($order['status'] != 'complete') {
            $this->error('操作失败');
        }

        $result           = false;
        $params['status'] = 'waitingpay';
        $result           = Db::name('express_package')->where('package_no', $from_express_no)->update($params);
        if ($result !== false) {
            $subscribe = new Subscribe();
            $template_id = 'cf8Kwi26XmmM0h4MBDXU95ElIpePSgKJiqmATjsdTlE';
            $page        = 'pages/Packagequery/Packagequery?type=payorder';
            $data        = [

                'character_string6' => $order['package_no'],
                'thing7' => '您的包裹已进行称重,支付后可进行发货'
            ];
            $subscribe->push($order['user_id'], $template_id, $page, $data);
            $this->success();
        } else {
            $this->error(__('No rows were inserted'));
        }
    }

    // 根据来源运单号查询包裹
    public function findForExpress()
    {
        $from_express_no = $this->request->post('from_express_no');
        if(empty($from_express_no)){
            $from_express_no = $this->request->get('from_express_no');
        }

        $type = 0;//1:包裹 2:订单
        $page = 'error';
        $express_order = "";
        if (strncmp($from_express_no,"ST",2) == 0) {
            //是包裹单号
            $type = 1;
            $express_order = Db::name('express_package')->where('package_no', $from_express_no)->find();
            if ($express_order['status'] == 'complete') {
                $page = 'weighing';
            } elseif ($express_order['state'] == 6) {
                $page = 'sign';
            } elseif ($express_order['state'] == 7) {
                $page = 'signed';
            }
        }

        if($type==0){
            //是订单
            $type = 2;
            $express_order = Db::name('express_order')->where('from_express_no', $from_express_no)->find();
            if(empty($express_order)){
                //完善订单
                $page = 'entry';
            }else{
                if ($express_order['package_id'] > 0) {
                    $page = 'package';//已经打包  跳转
                }else{
                    if($express_order['status'] == 'complete') {
                        $page = "store";
                    }elseif($express_order['is_forecast'] == 'yes') {
                        //是预报订单
                        if($express_order['is_now'] == 'yes') {
                            $page = 'store';
                        }else{
                            $page = 'store';
                        }
                    }
                }
            }
        }

        $data = [
            'page' => $page,
            'type' => $type,
            'from_express_no' => $from_express_no,
            'order' => $express_order,
        ];
        $this->success('ok', $data);
    }

    // 查询物流轨迹
    public function track()
    {
        $order_id = $this->request->param('order_id');
        $order    = model('app\api\model\Order')->get($order_id);
        if (!$order) {
            $this->error('该订包裹不存在');
        }
        $trackList = [];
        $track     = model('app\api\model\OrderTrack')
            ->where('order_id', $order_id)
            ->order('createtime desc')
            ->select();
        foreach ($track as $item) {

            $trackList[] = [
                'desc' => date('Y-m-d H:i:s', $item['createtime']),
                'text' => $item['state_text'],
            ];
        }

        $this->success('ok', $trackList);
    }

    public function lists(){
        $type = $this->request->get('type');//1:未入仓  2:在仓
        if ($type == 1) {
            $where['order.is_forecast'] = 'yes';//预报订单
            $where['order.package_id']  = 0;//没有打成包
            $where['order.status']      = 'created';//没有完善
        } elseif ($type == 2) {
            $where['order.package_id'] = 0;//没有打成包
            $where['order.status']     = 'complete';//已经完善
            $where['order.is_now']     = 'no';//不是立即
        }
        $where['order.user_id'] = $this->auth->id;
        $list = model('app\api\model\Order')
            ->with(['address'])
            ->where($where)
            //->where('address.name|address.mobile|address.address|address.idcard','like','%'.$keywords.'%')
            ->order('order.updatetime desc')
            ->paginate()->each(function($item,$key){
                return $item;
            });
        foreach ($list as $row) {
            $row->getRelation('address')->visible(['name', 'mobile', 'province', 'city', 'area', 'address', 'idcard', 'idcard_front', 'idcard_reverse', 'zip_code']);
        }
        $this->success('ok', $list);
    }

    //创建包裹
    public function createpackage()
    {
        $ids = $this->request->post("ids");
        $express_type = $this->request->post("express_type","");
        $address_id = (int)$this->request->post("address_id");
        $user_id     = $this->auth->id;
        if($user_id<1){
            $this->error('请登陆');
        }
        if(empty($ids)){
            $this->error('缺少订单id参数');
        }
        if(is_string($ids)){
            $ids = explode(",",$ids);
        }
        if($address_id < 1){
            $this->error('缺少地址id');
        }
        $order_list = Db::name('express_order')->where(['user_id'=>$user_id,'status'=>'complete'])->whereIn('id',$ids)->field(['id','user_id'])->select();
        if(empty($order_list)){
            $this->error('订单不存在');
        }
        $ids = array_column($order_list,'id');
        $nowTime = time();
        $packaage_no = orderOn($user_id);
        $packaage_id = Db::name('express_package')->insertGetId([
            'package_no' => $packaage_no,
            'user_id' => $user_id,
            'is_delivery' => 1,
            'status' => 'waitpackage',  //待打包
            'createtime' => $nowTime,
            'updatetime' => $nowTime,
            'express_type'=>$express_type
        ]);
        if($packaage_id<1){
            $this->error('包裹添加失败');
        }
        $address = model('app\api\model\Address')->where(['id'=>$address_id,'user_id'=>$user_id])->find();
        if(empty($address)) {
            $this->error('收货地址不存在');
        }
        //包裹地址，不存在添加，存在则修改
        $packAddressModel = PackageAddress::get([
            'package_id' => $packaage_id,
            'user_id' => $user_id,
        ]);
        if(empty($packAddressModel)){
            $packAddressModel = new PackageAddress();
        }
        $packAddressData = [
            'package_id' => $packaage_id,
            'user_id' => $user_id,
            'name' => $address['name'],
            'email' => $address['email'],
            'mobile' => $address['mobile'],
            'country' => $address['country'],
            'province' => $address['province'],
            'city' => $address['city'],
            'address' => $address['address'],
            'zip_code' => $address['zip_code'],
            'attachment_address' => $address['attachment_address'],
            'updatetime'=>$nowTime
        ];
        $packAddressModel->allowField(true)->save($packAddressData);
        //更新到order_id
        Db::name('express_order')->where('id', 'in', $ids)->update([
            'package_id' => $packaage_id,
            'package_no' => $packaage_no,
            'status'=>'waitpackage'
        ]);
        $this->success('');
    }



    //工作人员--包裹入库
    public function storeok()
    {
        $weight       = $this->request->param('weight');
        $volume       = $this->request->param('volume');
        $shelf_number = $this->request->param('volume');

        $from_express_no = $this->request->post('from_express_no');
        $image = $this->request->post('image');
        $express_order = Db::name('express_order')->where('from_express_no', $from_express_no)->find();
        if(empty($express_order)){
            $this->error('该快递不存在');
        }
        if(empty($image)){
            $this->error('请拍照上传图片');
        }

        $subscribe = new Subscribe();
        // $template_id = Config::get('site.new_order');
        $template_id = 'wxSCZ_IiXMVOSylHCNI7H0amN8OkF31BVCT3oZpyEXo';
        if ($express_order['is_now'] == 'yes') {
            //成生包裹
            $packaage_no = orderOn($express_order['user_id']);
            $packaage_id = Db::name('express_package')->insertGetId([
                'package_no' => $packaage_no,
                'user_id' => $express_order['user_id'],
                'is_delivery' => 1,
                'status' => 'waitpackage',
                'createtime' => time(),
                'updatetime' => time(),
            ]);
            $address_id  = Db::name('express_order_address')->where('order_id', $express_order['id'])->value('id');
            $address     = model('app\api\model\OrderAddress')->get($address_id);
            if (!$address) {
                $this->error('收货地址不存在');
            }
            $packAddressM = new PackageAddress();
            $packAddress  = $packAddressM->get([
                'package_id' => $packaage_id,
                'user_id' => $express_order['user_id'],
            ]);
            if ($packAddress) {
                $packAddressM->allowField(true)->save([
                    'package_id' => $packaage_id,
                    'user_id' => $express_order['user_id'],
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'province' => $address['province'],
                    'city' => $address['city'],
                    'area' => $address['area'],
                    'address' => $address['address'],
                    'zip_code' => $address['zip_code'],
                    'province_index' => $address['province_index'],
                    'city_index' => $address['city_index'],
                    'area_index' => $address['area_index'],
                ]);
            } else {
                $packAddressM = new PackageAddress();
                $packAddressM->allowField(true)->save([
                    'package_id' => $packaage_id,
                    'user_id' => $express_order['user_id'],
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'province' => $address['province'],
                    'city' => $address['city'],
                    'area' => $address['area'],
                    'address' => $address['address'],
                    'zip_code' => $address['zip_code'],
                ]);
            }
            Db::name('express_order')->where('from_express_no', $from_express_no)->update([
                'package_no' => $packaage_no,
                'package_id' => $packaage_id,
                'status' => 'waitpackage',
                'order_image'=>$image,
                'delivery_weight'=>$weight
            ]);
            $page = 'pages/Packagequery/Packagequery';
        } else {
            $page = 'pages/IndexServer/warehouse/warehouse';
            Db::name('express_order')->where('from_express_no', $from_express_no)->update([
                'status' => 'complete',  //已完善
                'order_image'=>$image
            ]);
        }

        //$string = '包裹已入库，重量：'.$weight.'KG，体积重：'.$volume.'KG';
        $string = '包裹已入库，请立即点击进行包裹预报';
        $data   = [
            'character_string1' => [
                'value' => $from_express_no
            ],
            'thing3' => [
                //'value' => '包裹已经完成入库，包裹重量为：'.$weight.'KGs，体积重：'.$volume.'KGs。请点击本条推送完善包裹预报信息，如果有任何问题请联系微信客服:qingau_express01'
                'value' => $string
            ]
        ];
        $subscribe->push($express_order['user_id'], $template_id, $page, $data);
        $this->success("ok");
    }

    //签收成功
    public function sign()
    {
        $from_express_no = $this->request->param('from_express_no');
        $image           = $this->request->param('image', '');
        $remark          = $this->request->param('remark', '');

        Db::name('express_package')->where('package_no', $from_express_no)->update([
            'state' => 7,
            'status' => 'sign',
            'image' => $image,
            'remark' => $remark
        ]);

        $this->success('签收成功');
    }

    //包裹轨迹
    public function packagetrack(){
        $package_id = $this->request->param('package_id');
        $list = Db::name('express_package_track')->where('package_id',$package_id)->order('createtime asc')->select();
        foreach ($list as $key=>$value){
            $list[$key]['createtime'] = date('Y-m-d H:i',$value['createtime']);
            //状态:0=已入库,1=已预报,2=包裹已出库,3=正在发往澳洲,4=包裹清关中,5=包裹清关完成，等待发往指定地点,6=包裹已抵达指定自提点，等待顾客取件,7=已签收
            if($value['state']==0){
                $list[$key]['state_txt'] = '已入库';
            }elseif ($value['state']==1){
                $list[$key]['state_txt'] = '已预报';
            }elseif ($value['state']==2){
                $list[$key]['state_txt'] = '包裹已出库';
            } elseif ($value['state']==3){
                $list[$key]['state_txt'] = '正在发往目的地';
            }elseif ($value['state']==4){
                $list[$key]['state_txt'] = '包裹清关中';
            }elseif ($value['state']==5){
                $list[$key]['state_txt'] = '包裹清关完成,等待发目的地';
            }elseif ($value['state']==6){
                $list[$key]['state_txt'] = '包裹已抵达目的地，等待顾客取件';
            }elseif ($value['state']==7){
                $list[$key]['state_txt'] = '已签收';
            }
        }
        $this->success('物流轨迹',$list);
    }


    //估算运费
    public function counter()
    {
        if (request()->isPost()) {
            $post   = $this->request->param('row/a');
            if (!isset($post['length'])||empty($post['length'])) {
                $post['length'] = 0;
            }
            if (!isset($post['wide'])||empty($post['wide'])) {
                $post['wide'] = 0;
            }
            if (!isset($post['high'])||empty($post['high'])) {
                $post['high'] = 0;
            }
            if (!isset($post['num'])||empty($post['num'])) {
                $post['num'] = 0;
            }
            $weight = "";//重量
            if (isset($post['weight'])&&$post['weight']>0) {
                $weight = $post['weight'];
            }
            $length = $post['length'];//长
            $wide   = $post['wide'];//宽
            $high   = $post['high'];//高
            $num    = $post['num'];//数量

            $volume_weight_key = (int)$post['volume_weight_price'];//体积重
            $volume_weight = 0;
            if($volume_weight_key>0){
                $volume_weight = $wide * $high * $length / $volume_weight_key  *  $num;//体积重
            }

            $volume = $wide * $high * $length / 1000000;//立方米
            $w = 0;
            if (!empty($weight)) {
                if ($volume_weight >= $weight) {
                    $w = $volume_weight;
                } else {
                    $w = $weight;
                }
            }

            if (empty($weight)) {
                $w = $volume_weight;
            }
            $volume_weight = round($volume_weight, 2);
            $w = round($w, 2);
            $list = Db::name('express_counter')->where('status', 'normal')->where('deletetime', NULL)->select();
            foreach ($list as $key => $value) {
                $list[$key]['price'] = $this->js($w, (float)$value['first_weight'], (float)$value['first_price'], (float)$value['additional_weight_ladder'], (float)$value['additioinal_price']);
            }
            $this->success('',['volume_weight'=>$volume_weight,'volume'=>$volume,'result'=>$list]);
        }
    }

    //运费计算
    protected  function js($w, $first_weight, $first_price, $additional_weight_ladder, $additioinal_price)
    {
        $price = 0;
        $additional_weight_ladder = $additional_weight_ladder<=0?1:$additional_weight_ladder;
        if ($w <= $first_weight) {
            $price += $first_price;
        } elseif ($w > $first_weight) {
            $price += $first_price;
            $price += ceil(($w - $first_weight) / $additional_weight_ladder) * $additioinal_price;
        }
        return   sprintf("%.2f",$price);
    }

    public function express_type(){
       $list =  Db::name('express_counter')->where('status','normal')->field('id,name')->select();
       $this->success('ok',$list);
    }


    //订单物流信息
    public function getExpressInfo(){
        $request = $this->request;
        $user_id = $this->auth->id;
        $id = (int)$request->post('id');
        if($id<1){
            $this->error("缺少包裹参数");
        }

        $package = Db::name('express_package')->where(['id'=>$id,'user_id'=>$user_id])->find();
        if(empty($package)){
            $this->error("包裹不存在");
        }
        if(empty($package['express_no'])){
            $this->error("还未有物流单号");
        }
        try{
            $expressData = PackageExpress::getExpressData($package['package_no'],$package['express_no']);
            if(empty($expressData)){
                $expressData = PackageExpress::setExpressData($package['package_no'],$package['express_no']);
            }
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $data=[
            'expressData'=>$expressData['data']??[]
        ];
        $this->success('ok',$data);
    }

    //添加包裹
    public function addPack(){
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $admin_id = $this->auth->id;
        $user_id = (int)$this->request->post("user_id",0);
        $image = $this->request->post("image");
        $delivery_weight = $this->request->post("delivery_weight");
        $remark = $this->request->post("remark","");
        $goods = $_POST['goods']??"";

        $name = $this->request->post("name");
        $mobile = $this->request->post("mobile");
        $province = $this->request->post("province");
        $city = $this->request->post("city");
        $area = $this->request->post("area");
        $address = $this->request->post("address");
        $zip_code = $this->request->post("zip_code");

        if($user_id<1){
            $this->error("请填写用户ID");
        }
        $user = Db::name('user')->where("id",$user_id)->find();
        if(empty($user)){
            $this->error("用户信息不存在");
        }
        if(empty($image)){
            $this->error("请上传包裹图片");
        }
        $delivery_weight = sprintf("%.2f",$delivery_weight);
        if($delivery_weight<=0){
            $this->error("请填写重量");
        }
        $goods1 = $goods;
        if(empty($goods)){
            $this->error("请添加商品1");
        }
        if(is_string($goods)){
            $goods = json_decode($goods,true);
        }
        if(empty($goods) || !is_array($goods)){
            $this->error("请添加商品",$goods1);
        }
        $goods_list = [];
        foreach ($goods as $goodsInfo){
            if(empty($goodsInfo) || !is_array($goodsInfo)){
                continue;
            }
            $goods_name = $goodsInfo['name']??"";
            $number = (int)($goodsInfo['number']??1);
            $number = $number<1?1:$number;
            $weight = $goodsInfo['weight']??1;
            $price = $goodsInfo['price']??1;
            $weight = sprintf("%.2f",$weight);
            $price = sprintf("%.2f",$price);

            $goods_list[]=[
                "name"=>$goods_name,
                "number"=>$number,
                "weight"=>$weight,
                "price"=>$price,
            ];
        }
        if(empty($goods_list)){
            $this->error("请添加商品");
        }
        if(empty($name)){
            $this->error("请填写收货人名称");
        }
        if(empty($mobile)){
            $this->error("请填写手机号");
        }
        if(!preg_match("/^[0-9]{8,12}$/",$mobile)){
            $this->error("手机号格式不正确");
        }
        if(empty($province)){
            $this->error("请填写收货地址-省");
        }
        if(empty($city)){
            $this->error("请填写收货地址-城市");
        }
        if(empty($area)){
            $this->error("请填写收货地址-区/县");
        }
        if(empty($address)){
            $this->error("请填写收货地址-详细地址");
        }

        $nowTime = time();
        $address_data = [
            "user_id"=>$user_id,
            "name"=>$name,
            "mobile"=>$mobile,
            "province"=>$province,
            "city"=>$city,
            "area"=>$area,
            "address"=>$address,
            "zip_code"=>$zip_code,
            "createtime"=>$nowTime,
            "updatetime"=>$nowTime
        ];
        $package_no = orderOn($user_id);
        $package_data = [
            'package_no' => $package_no,
            'user_id' => $user_id,
            'is_delivery' => 1,
            'status' => 'waitpackage',  //待打包
            'createtime' => $nowTime,
            'updatetime' => $nowTime,
            'image'=>$image,
            'delivery_weight'=>$delivery_weight,
            'remark'=>$remark,
            'express_type'=>"",
            'admin'=>"user=".$admin_id
        ];

        $model = new \app\admin\model\express\Package;
        Db::startTrans();
        try {
            $package_id = $model->allowField(true)->insertGetId($package_data);
            if($package_id<1){
                throw new Exception("包裹添加失败");
            }
            foreach ($goods_list as &$goods){
                $goods['package_id'] = $package_id;
            }
            $res = model('app\admin\model\ExpressPackageGoods')->saveAll($goods_list);
            if(empty($res)){
                throw new Exception("包裹物品添加失败");
            }
            $address_data['package_id'] = $package_id;
            $res = Db::name("express_package_address")->insert($address_data);
            if(empty($res)){
                throw new Exception("包裹地址添加失败");
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error("失败：".$e->getMessage());
        }
        $pages = "pages/Packagequery/Packagequery";
        TemplateSub::sendTemplate($user_id,$package_no,"包裹已提交",$pages);
        $this->success("添加成功");
    }

    //包裹详情
    public function packDetail(){
        $id = (int)$this->request->param("id",0);
        if($id<1){
            $this->error("缺少参数");
        }
        $package_fields = ["id","package_no",'image','delivery_weight','remark',"user_id","state","status","createtime"];
        $packageInfo = Db::name("express_package")->field($package_fields)->where("id",$id)->find();
        if(empty($packageInfo)){
            $this->error("包裹不存在");
        }
        $model = new Package();
        $packageInfo['http_image'] = cdnurl($packageInfo['image'],true);
        $packageInfo['status_text'] = $model->getStatusTextAttr($packageInfo['status'],"");
        $packageInfo['state_text'] = $model->getStateTextAttr($packageInfo['state'],"");

        $user_id = $packageInfo['user_id'];
        $userInfo = Db::name("user")->field(["id",'nickname','avatar'])->where("id",$user_id)->find();
        $goods_fields = ["id","name","weight","number","price"];
        $goods_list = Db::name("express_package_goods")->field($goods_fields)->where("package_id",$id)->select();
        $address_fields = ["id","name","mobile","province","city","area","address","zip_code"];
        $addressInfo = Db::name("express_package_address")->field($address_fields)->where("package_id",$id)->find();

        $data = [
            "package"=>$packageInfo,
            "user"=>$userInfo,
            'goods'=>$goods_list,
            'address'=>$addressInfo
        ];
        $this->success("ok",$data);
    }

    //包裹编辑
    public function editPack(){
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $admin = "user=".$this->auth->id;
        $id = (int)$this->request->post("id",0);
        $image = $this->request->post("image");
        $delivery_weight = $this->request->post("delivery_weight");
        $remark = $this->request->post("remark","");
        $goods = $_POST['goods']??"";
        $name = $this->request->post("name");
        $mobile = $this->request->post("mobile");
        $province = $this->request->post("province");
        $city = $this->request->post("city");
        $area = $this->request->post("area");
        $address = $this->request->post("address");
        $zip_code = $this->request->post("zip_code");

        if($id<1){
            $this->error("缺少包裹id");
        }
        $packageInfo = Db::name('express_package')->where(["id"=>$id,"admin"=>$admin])->find();
        if(empty($packageInfo)){
            $this->error("包裹信息不存在");
        }
        if($packageInfo['status'] != "waitpackage"){
            $this->error("该包裹不能被编辑");
        }
        $user_id = $packageInfo['user_id'];
        if(empty($image)){
            $this->error("请上传包裹图片");
        }
        $delivery_weight = sprintf("%.2f",$delivery_weight);
        if($delivery_weight<=0){
            $this->error("请填写重量");
        }
        if(empty($goods)){
            $this->error("请添加商品");
        }
        if(is_string($goods)){
            $goods = json_decode($goods,true);
        }
        if(empty($goods) || !is_array($goods)){
            $this->error("请添加商品");
        }
        $old_goods_list = Db::name("express_package_goods")->select(['id','package_id'])->where("package_id",$id)->select();
        $old_goods_ids = $old_goods_list?array_column($old_goods_list,'id'):[];
        $goods_list = [];
        $goods_ids = [];
        foreach ($goods as $goodsInfo){
            if(empty($goodsInfo) || !is_array($goodsInfo)){
                continue;
            }
            $goods_name = $goodsInfo['name']??"";
            $number = (int)($goodsInfo['number']??1);
            $number = $number<1?1:$number;
            $weight = $goodsInfo['weight']??1;
            $price = $goodsInfo['price']??1;
            $weight = sprintf("%.2f",$weight);
            $price = sprintf("%.2f",$price);
            $goods_id = (int)$goodsInfo['id'];
            if($goods_id>0 && !in_array($goods_id,$old_goods_ids)){
                continue;
            }
            if($goods_id>0){
                $goods_ids[] = $goods_id;
            }
            $goods_list[]=[
                "id"=>$goods_id>0?$goods_id:null,
                "package_id"=>$id,
                "name"=>$goods_name,
                "number"=>$number,
                "weight"=>$weight,
                "price"=>$price,
                "createtime"=>time(),
                "updatetime"=>time()
            ];
        }
        if(empty($goods_list)){
            $this->error("请添加商品");
        }
        $diff_goods_ids = array_diff($old_goods_ids,$goods_ids);
        if(empty($name)){
            $this->error("请填写收货人名称");
        }
        if(empty($mobile)){
            $this->error("请填写手机号");
        }
        if(!preg_match("/^[0-9]{8,12}$/",$mobile)){
            $this->error("手机号格式不正确");
        }
        if(empty($province)){
            $this->error("请填写收货地址-省");
        }
        if(empty($city)){
            $this->error("请填写收货地址-城市");
        }
        if(empty($area)){
            $this->error("请填写收货地址-区/县");
        }
        if(empty($address)){
            $this->error("请填写收货地址-详细地址");
        }

        $nowTime = time();
        $address_data = [
            "package_id"=>$id,
            "user_id"=>$user_id,
            "name"=>$name,
            "mobile"=>$mobile,
            "province"=>$province,
            "city"=>$city,
            "area"=>$area,
            "address"=>$address,
            "zip_code"=>$zip_code,
            "createtime"=>$nowTime,
            "updatetime"=>$nowTime
        ];
        $package_data = [
            'user_id' => $user_id,
            'updatetime' => $nowTime,
            'image'=>$image,
            'delivery_weight'=>$delivery_weight,
            'remark'=>$remark,
        ];

        $addressModel = model('app\api\model\ExpressPackageGoods')->where("package_id",$id)->find();
        if(empty($addressModel)){
            $addressModel = new PackageAddress();
        }
        Db::startTrans();
        try {
            $res = Db::name("express_package")->where("id",$id)->update($package_data);
            if(empty($res)){
                throw new Exception("包裹修改失败");
            }
            $res = model('app\admin\model\ExpressPackageGoods')->saveAll($goods_list);
            if(empty($res)){
                throw new Exception("包裹物品添加失败");
            }
            //删除多余的商品
            if($diff_goods_ids && is_array($diff_goods_ids)){
                Db::name("express_package_goods")->whereIn("id",$diff_goods_ids)->delete();
            }
            $res = $addressModel->save($address_data);
            if(empty($res)){
                throw new Exception("包裹地址添加失败");
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("添加成功");
    }

    //包裹列表
    public function packList(){
        if ($this->auth->isworker == 0) {
            $this->error('您无权进行此操作');
        }
        $admin = "user=".$this->auth->id;
        $page = $this->request->param("page",1);
        $page = $page>0?$page:1;
        $size = 10;

        $fields = ["id","batch_id","package_no","user_id","state","image","status","delivery_weight","delivery_price","express_no","express_name","createtime"];
        $query = Db::name("express_package")
            ->where(["admin"=>$admin])
            ->field($fields)->order("id","desc");

        $list = $query->paginate($size)->toArray();
        if($list['data']){
            $user_ids = array_column($list['data'],"user_id");
            $user_list = Db::name("user")->whereIn("id",$user_ids)->field(['id','nickname','avatar'])->select();
            $user_ar = [];
            foreach ($user_list as $k=>$val){
                $user_ar[$val['id']] = $val;
            }
            $model = new Package();
            foreach ($list['data'] as &$list_val){
                $list_val['userInfo'] = $user_ar[$list_val['user_id']]??"";
                $list_val['image'] = cdnurl($list_val['image'],true);
                $list_val['status_text'] = $model->getStatusTextAttr($list_val['status'],"");
                $list_val['state_text'] = $model->getStateTextAttr($list_val['state'],"");
            }
        }

        $this->success("ok",$list);
    }


    //用户包裹列表
    public function userPackList(){
        $user_id = $this->auth->id;
        $type = $this->request->param("type"); //1 待发货，2，已发货，3已抵达，4，已发快递
        $page = $this->request->param("page",1);
        $page = $page>0?$page:1;
        $size = 10;

        $fields = ["id","batch_id","package_no","user_id","state","image","status","delivery_weight","delivery_price","express_no","express_name","createtime"];
        $query = Db::name("express_package")
            ->where(["user_id"=>$user_id])->field($fields)->order("id","desc");
        if($type==1){
            $query->whereIn("state",["1","2"]);
        }elseif($type==2){
            $query->whereIn("state",["3","4","5"]);
        }elseif($type==3){
            $query->whereIn("state",["6"]);
        }elseif($type==4){
            $query->whereIn("state",["7"]);
        }
        $list = $query->paginate($size)->toArray();
        if($list['data']){
            $user_ids = array_column($list['data'],"user_id");
            $user_list = Db::name("user")->whereIn("id",$user_ids)->field(['id','nickname','avatar'])->select();
            $user_ar = [];
            foreach ($user_list as $k=>$val){
                $user_ar[$val['id']] = $val;
            }
            $model = new Package();
            foreach ($list['data'] as &$list_val){
                $list_val['userInfo'] = $user_ar[$list_val['user_id']]??"";
                $list_val['image'] = cdnurl($list_val['image'],true);
                $list_val['status_text'] = $model->getStatusTextAttr($list_val['status'],"");
                $list_val['state_text'] = $model->getStateTextAttr($list_val['state'],"");
            }
        }

        $this->success("ok",$list);
    }


    public function test(){
        $goods_list = [];
        $goods_list[]=[
            "id"=>1,
            "name"=>"aaaff8888",
            "updatetime"=>time(),
        ];
        $goods_list[]=[
            "id"=>2,
            "name"=>"aaass117777",
            "updatetime"=>time(),
        ];
        $goods_list[]=[
            "id"=>null,
            "name"=>"aaass11",
            "updatetime"=>time(),
        ];
        $model = new PackageAddress();
        $res = $model->saveAll($goods_list);
        dump($res);die;
    }



}
